package com.neusoft.service.impl;

import com.neusoft.core.*;
import com.neusoft.feign.FoodFeignClient;
import com.neusoft.feign.PointFeighClient;
import com.neusoft.feign.VirtualWalletFeignClient;
import com.neusoft.mapper.CartMapper;
import com.neusoft.mapper.OrderDetailetMapper;
import com.neusoft.mapper.OrdersMapper;
import com.neusoft.service.OrdersService;
import com.neusoft.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
    @Autowired
    private PointFeighClient pointFeighClient;
	@Autowired
	private FoodFeignClient foodFeignClient;
	@Autowired
	private VirtualWalletFeignClient virtualWalletFeignClient;
	private final Lock lock = new ReentrantLock();
	@Override
	@Transactional
	public int createOrders(Orders orders) {
		//1、查询当前用户购物车中当前商家的所有食品
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartList = cartMapper.listCart(cart);
		
		//2、创建订单（返回生成的订单编号）
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);
		int orderId = orders.getOrderId();
		
		//3、批量添加订单明细
		List<OrderDetailet> list = new ArrayList<>();
		for(Cart c : cartList) {
			OrderDetailet od = new OrderDetailet();
			od.setOrderId(orderId);
			od.setFoodId(c.getFoodId());
			od.setQuantity(c.getQuantity());
			list.add(od);
		}
		orderDetailetMapper.saveOrderDetailetBatch(list);
		
		//4、从购物车表中删除相关食品信息
		cartMapper.removeCart(cart);
		
		return orderId;
	}
	
	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}
@SuppressWarnings("finally")
@Override
public List<String> finishOrders(Integer orderId, Integer orderType, Integer fromWalletId, Integer toWalletId, BigDecimal amount) {
    lock.lock();
    try {
        List<String> show = new ArrayList<>();
        
        // 获取订单信息
        Orders order = ordersMapper.getOrdersById(orderId);
        if (order == null) {
            show.add("订单不存在");
            return show;
        }
        
        // 如果传入了新的订单金额，则更新订单金额
        if (amount != null) {
            ordersMapper.updateOrderTotal(orderId, amount.doubleValue());
            // 更新本地order对象
            order.setOrderTotal(amount.doubleValue());
            System.out.println("订单金额已更新为: " + amount);
        }
        
        // 1. 检查商品库存
        List<OrderDetailet> orderDetailets = orderDetailetMapper.listOrderDetailetByOrderId(orderId);
        for (OrderDetailet od : orderDetailets) {
            Integer foodId = od.getFoodId();
            Food food = foodFeignClient.getFoodById(foodId).getResult();
            Integer foodQuantity = food.getQuantity();
            Integer odQuantity = od.getQuantity();
            if (foodQuantity < odQuantity) {
                show.add(food.getFoodName() + "数量不足");
            }
        }

        if (!show.isEmpty()) {
            return show;
        }
        
        // 2. 处理钱包支付
        if (orderType == 2) {
            try {
                // 打印调试信息
                System.out.println("===== 钱包支付调试信息 =====");
                System.out.println("订单ID: " + orderId);
                System.out.println("订单金额: " + order.getOrderTotal());
                System.out.println("用户钱包ID: " + fromWalletId);
                System.out.println("商家钱包ID: " + toWalletId);
                
                // 使用最新的订单金额进行转账
                BigDecimal payAmount = BigDecimal.valueOf(order.getOrderTotal());
                virtualWalletFeignClient.transfer(fromWalletId, toWalletId, payAmount);
                System.out.println("钱包支付成功");
                
                // 用户积分更新
                BigDecimal change = payAmount.multiply(new BigDecimal("10000"));
                Integer longValue = change.intValueExact(); // 精确转换
                PointLog pointLog = new PointLog();
                pointLog.setUserId(order.getUserId());
                pointLog.setChange(longValue);
                pointLog.setReason("消费");
                pointFeighClient.addPointLog(pointLog);
            } catch (Exception e) {
                // 详细记录异常信息
                System.err.println("钱包支付异常详情: " + e.getMessage());
                e.printStackTrace();
                show.add("钱包支付失败: " + e.getMessage());
                return show;
            }
        }
        // 处理在线支付(支付宝/微信)
        else if (orderType == 1) {
            try {
                // 打印调试信息
                System.out.println("===== 在线支付调试信息 =====");
                System.out.println("订单ID: " + orderId);
                System.out.println("订单金额: " + order.getOrderTotal());
                System.out.println("商家钱包ID: " + toWalletId);
                
                // 使用最新的订单金额给商家钱包增加余额
                BigDecimal payAmount = BigDecimal.valueOf(order.getOrderTotal());
                virtualWalletFeignClient.credit(toWalletId, payAmount);
                
                System.out.println("在线支付成功，商家钱包已增加余额");
                
                // 用户积分更新
                BigDecimal change = payAmount.multiply(new BigDecimal("10000"));
                Integer longValue = change.intValueExact(); // 精确转换
                PointLog pointLog = new PointLog();
                pointLog.setUserId(order.getUserId());
                pointLog.setChange(longValue);
                pointLog.setReason("消费");
                pointFeighClient.addPointLog(pointLog);
            } catch (Exception e) {
                // 详细记录异常信息
                System.err.println("在线支付异常详情: " + e.getMessage());
                e.printStackTrace();
                show.add("在线支付失败: " + e.getMessage());
                return show;
            }
        }
        
        // 3. 扣减库存并完成订单
        for (OrderDetailet od : orderDetailets) {
            Integer foodId = od.getFoodId();
            Integer odQuantity = od.getQuantity();
            foodFeignClient.orderFood(new Food(foodId, odQuantity));
        }
        
        // 4. 更新订单状态
        ordersMapper.finishOrders(orderId);
        
        return show; // 返回空列表表示成功
    } finally {
        lock.unlock();
    }
}
}
